<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use think\Db;

class Loan extends Api
{
    public function add()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            if(!isset($post['user_id'])){
                return fh(1,'error','缺少用户id',[]);
            }
            if(!isset($post['id'])){
                return fh(1,'error','缺少贷款额度id',[]);
            }
            Db::startTrans();
            try{
                $model = model('loansetting')->where('id','=',$post['id'])->find()->toArray();
                $integraldetailed = model('integraldetailed')->where([
                    ['user_id','=',$post['user_id']],
                    ['status','=',3]
                ])->select()->toArray();
                $money = 0;
                foreach ($integraldetailed as $k=>$v){
                    if($v['class'] == 1){
                        $money = $money + $v['num'];
                    }else{
                        $money = $money - $v['num'];
                    }
                }
                if($money < $model['integral']){
                    return fh(1,'error','积分不足',[]);
                }
                $user = model('user')->get($post['user_id'])->toArray();
                $loan = $user['loan']*1 + $model['integral']*1;
                model('user')->save(['loan'=>$loan],['id'=>$user['id']]);
                model('integral')->save(['num'=>$model['integral'],'status'=>2,'user_id'=>$user['id'],'source'=>3]);
                $integralid = model('integral')->id;
                model('integraldetailed')->save(['integral_id'=>$integralid,'num'=>$model['integral'],'class'=>2,'user_id'=>$user['id'],'status'=>3]);
                model('loan')->save(['create_time'=>date('Y-m-d H:i:s'),'user_id'=>$user['id'],'money'=>$model['integral'],'status'=>30,'name'=>$user['name']]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return fh(500,'error',$e->getMessage(),[]);
            }
            return fh(200,'success','添加贷款额度成功',[]);
        }
    }
}
